package xin.yangshuai.mybatisgeneratorweb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.yangshuai.mybatisgeneratorweb.model.DataCodeInfo;
import xin.yangshuai.mybatisgeneratorweb.service.DataCodeInfoService;
import xin.yangshuai.mybatisgeneratorweb.util.DownloadUtils;
import xin.yangshuai.mybatisgeneratorweb.vo.BaseResponse;
import xin.yangshuai.mybatisgeneratorweb.vo.DataCodeDownloadVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * DataCodeInfoController
 *
 * @author shuai
 * @date 2021/7/29
 */
@RestController
@RequestMapping("dataCodeInfo")
public class DataCodeInfoController {

    @Autowired
    private DataCodeInfoService dataCodeInfoService;

    @PostMapping("basic")
    public String basic(DataCodeInfo dataCodeInfo) throws Exception {
        try {
            return dataCodeInfoService.createDataCode(dataCodeInfo);
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @RequestMapping("query")
    public BaseResponse query() {

        List<DataCodeDownloadVO> list = dataCodeInfoService.query();

        return BaseResponse.success(list);
    }

    @RequestMapping("download")
    public void download(Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {

        DataCodeDownloadVO dataCodeDownloadVO = dataCodeInfoService.selectById(id);

        File file = new File(dataCodeDownloadVO.getDownloadPath());

        DownloadUtils.download(file, request, response);
    }
}
